<?php
namespace App\Services;

use App\Models\Cart;
use Illuminate\Support\Facades\DB;
//use Illuminate\Support\Facades\Session;
/**
 *
 * 购物车服务层
 *
 * @author shengl@maqu.im
 *
 */
class CartService extends BaseService {

    /**
     * 获取商品种类数
     *
     * @param $sess_id session id
     * @param $user_id 用户id
     * @return int $kinds 商品种类数
     */
    public function getKinds($sess_id, $user_id = 0)
    {
        $query = Cart::where('session_id','=',$sess_id);

        if($user_id){
            $query->where('user_id','=',$user_id);
        }

        $kinds = $query->distinct('goods_id')->count();

        return $kinds;
    }

    /**
     *以购物车为单位获取购物车列表及商品项
     *
     * @param int $user_id
     * @param array $rec_ids
     * @return array
     */
    public function getCarts($user_id=0,$rec_ids=[])
    {
        //获取购物车数据列表
        $query = DB::table('cart')
            ->join('store', 'cart.store_id', '=', 'store.store_id')
            ->join('goods','goods.goods_id','=','cart.goods_id')
            ->join('goods_spec','cart.spec_id','=','goods_spec.spec_id');

        if($user_id){
            $query->where('cart.user_id',$user_id);
        }else{
            $query->where('cart.session_id',session_id());
        }

        if(count($rec_ids)>0){
            //$query->where('tb_cart.rec_id in ('.implode(',',$rec_ids).')');
            $query->whereIn('cart.rec_id',$rec_ids);
        }

        $list = $query->select('cart.rec_id','cart.store_id','cart.goods_id','cart.goods_name','cart.spec_id',
                'cart.specification','cart.price','cart.quantity','cart.goods_image','cart.goods_type',
                'cart.sku','cart.extra_info','store.store_id','store.store_name','goods_spec.spec_1',
                'goods_spec.price','goods_spec.stock','goods.is_set','store.config')->get();

        //编辑数据
        $carts = [
            'status' => [
                'kinds' => 0,
                'sub_amount' => 0,
                'quantity' => 0,
            ],
            'store' => []
        ];

        if (empty($list)) {
            return $carts;
        }

        foreach($list as $object)
        {
            $cart_items[] =  (array) $object;
        }

        $def_arr =[
            'store_info' => [
                'store_id' => 0,
                'store_name' => '',
                'shipping_fee_info' => '',
            ],
            'total_store' => [
                'kinds' => 0,
                'amount' => 0,
                'quantity' => 0,
            ],
            'goods' => []
        ];

        $temp_arr=[];

        foreach ($cart_items as $k=> $item)
        {
            if(!array_key_exists($item['store_id'],$carts['store'])){
                $temp_arr = $def_arr;
            } else {
                $temp_arr = $carts['store'][$item['store_id']];
            }

            $totalPrice = $item['price'] * $item['quantity'];

            /* 总计 */
            $carts['status']['sub_amount'] += $totalPrice;
            $carts['status']['quantity'] += $item['quantity'];
            $carts['status']['kinds'] += 1;
            /* 编辑店铺信息 */
            $temp_arr['store_info']['store_id']    = $item['store_id'];
            $temp_arr['store_info']['store_name']    = $item['store_name'];

            $configs= json_decode($item['config']);
            $config['shipping'] = (array)$configs->shipping;
            $temp_arr['store_info']['shipping_fee_info'] = "满".$config['shipping']['min_free']."元包邮,不足金额运费".$config['shipping']['shipping_fee']."元";
            //店铺小计
            $temp_arr['total_store']['kinds']     += 1;
            $temp_arr['total_store']['amount']     += $totalPrice;   //各店铺的总金额
            $temp_arr['total_store']['quantity']     += $item['quantity'];   //各店铺的总数量

            /* 商品缩略图 */
            empty($item['goods_image']) && $item['goods_image'] = env('default_goods_image');
            $item['goods_image'] = complete_url($item['goods_image']);

            /* 加入商品信息 */
            $temp_arr['goods'][] =$item;

            $carts['store'][$item['store_id']]=$temp_arr;
            unset($temp_arr);
        }

        //去除store_id的key值
        $carts['store'] = array_values($carts['store']);

        return $carts;
    }

    /**
     * 获取购物车数量
     *
     * @param $user_id 用户id
     * @param int $rec_id 购物车id
     * @return  int  数量
     *
     */
    public function getCartCount($user_id,$rec_id = 0)
    {
        $query = DB::table('cart')
            ->join('store', 'cart.store_id', '=', 'store.store_id')
            ->join('goods_spec','cart.spec_id','=','goods_spec.spec_id')
            ->join('goods','goods.goods_id','=','cart.goods_id');

        if($user_id){
            $query->where('cart.user_id',$user_id);
        }else{
            $query->where('cart.session_id',session_id());
        }

        if($rec_id){
            $query->where('cart.rec_id',$rec_id);
        }

        //$cart_count = $query->orderBy('cart.store_id','asc')->count();
        $carts =$query->orderBy('cart.store_id','asc')->select('cart.quantity')->get();
        $cart_count =0;
        foreach($carts as $item){
            $cart_count+=$item->quantity?$item->quantity:0;
        }
        return $cart_count;

    }

    /**
     *    获取购物车状态
     *
     *    @author    maqu
     *    @return    array
     */
    public function getCartStatus($user_id)
    {
        /* 默认的返回格式 */
        $data = [
            'status'    =>  [
                'quantity'  =>  0,      //总数量
                'amount'    =>  0,      //总金额
                'kinds'     =>  0,      //总种类
            ],
            'carts'     =>  [],    //购物车列表，包含每个购物车的状态
        ];

        /* 获取所有购物车 */
        $carts = $this->getCarts($user_id);

        if (empty($carts))
        {
            return $data;
        }
        $data['carts']  =   $carts;

        $data['status']['quantity'] = $carts['status']['quantity'];
        $data['status']['amount']   = $carts['status']['sub_amount'];
        $data['status']['kinds']    = $carts['status']['kinds'];

        return $data;
    }

    /**
     *  获取购物车信息
     *
     *
     */
    public function getCartInfo($rec_id=0,$user_id=0,$spec_id=0){
        $query = DB::table('cart');
        if($rec_id)
            $query->where('rec_id',$rec_id);

        if($user_id){
            $query->where('user_id',$user_id);
        }else{
            $query->where('session_id',session_id());
        }

        if($spec_id)
            $query->where('spec_id',$spec_id);

        $cart = $query->first();

        return $cart;
    }

    /**
     *  获取购物车列表
     *
     */
    public function getCartList($rec_ids,$user_id=0,$spec_id=0){
        $query = DB::table('cart');
        if($rec_ids){
            //$query->whereRaw('cart.rec_id in ('.implode(",",$rec_ids).')');
            if(is_int($rec_ids)){
                $query->where('cart.rec_id',$rec_ids);
            } else {
                $query->whereIn('cart.rec_id',$rec_ids);
            }
        }

        if($user_id){
            $query->where('cart.user_id',$user_id);
        }else{
            $query->where('cart.session_id',session_id());
        }

        if($spec_id)
            $query->where('cart.spec_id',$spec_id);

        $cart = $query->groupBy('cart.rec_id')->get();

        return $cart;
    }

    /**
     *  查询商品是否已经在购物车中
     * @param $spec_id 规格id
     * @param $user_id 用户id
     * @return int count 数量
     */
    public function specInCart($spec_id,$user_id=0){

        /* 是否添加过 */
        $query = Cart::where('spec_id',$spec_id);

        if($user_id){
            $query-> where('user_id',$user_id);
        }else{
            $query-> where('session_id',session_id());
        }

        $cart=$query ->first();

        return $cart;
    }

    /**
     *加入购物车
     *
     * @param $spec_info 商品规格数据
     * @param $user_id 用户id
     * @param $quantity 数量
     * @throws Exception
     * @throws \Exception
     *
     */
    public function addToCart($spec_info,$user_id,$quantity){

        $temp_cart = $this->specInCart($spec_info->spec_id,$user_id);

        if($temp_cart){
            $this->modifyQuantity($temp_cart->rec_id,$temp_cart->quantity+$quantity);
        } else{

            DB::beginTransaction();

            try {
                $spec_1 = $spec_info->spec_name_1 ? $spec_info->spec_name_1 . ':' . $spec_info->spec_1 : $spec_info->spec_1;
                $spec_2 = $spec_info->spec_name_2 ? $spec_info->spec_name_2 . ':' . $spec_info->spec_2 : $spec_info->spec_2;

                if($spec_info->spec_name_1 && $spec_info->spec_name_2){
                    $specification =  $spec_1 . ' ' . $spec_2;
                }elseif($spec_info->spec_name_1 && !$spec_info->spec_name_2 ){
                    $specification =  $spec_1;
                }elseif($spec_info->spec_name_2 && !$spec_info->spec_name_1){
                    $specification =  $spec_2;
                }else{
                    $specification = "";
                }

                /* 将商品加入购物车 */
                $cart_item = array(
                    'user_id'       => $user_id,
                    'session_id'    => session_id(),
                    'store_id'      => $spec_info->store_id,
                    'spec_id'       => $spec_info->spec_id,
                    'goods_id'      => $spec_info->goods_id,
                    'goods_name'    => addslashes($spec_info->goods_name),
                    'specification' => addslashes(trim($specification)),
                    'price'         => $spec_info->price,
                    'quantity'      => $quantity,
                    'goods_image'   => addslashes($spec_info->default_image2),
                );

                if(empty($spec_info->default_image2)){
                    $cart_item['goods_image'] = addslashes($spec_info->default_image);
                }

                /* 添加并返回购物车统计即可 */
                Cart::insert($cart_item);

                /* 更新被添加进购物车的次数 */
                DB::table('goods_statistics')->where('goods_id',$spec_info->goods_id)->increment('carts');

                DB::commit();

            } catch (Exception $e) {
                DB::rollback();
                throw $e;
            }
        }

    }

    /**
     * 修改数量
     * @param $rec_id 购物车id
     * @param $quantity 修改的数量
     * @return  null
     */
    public function modifyQuantity($rec_id,$quantity){
        /* 修改数量 */
       Cart::where('rec_id',$rec_id)
            ->update(array(
                'quantity'  =>  $quantity,
            ));
    }

    /**
     * 修改规格
     * @param $rec_id 购物车id
     * @param $new_spec_id 修改后的规格id
     * @param $specification 修改后的规格信息
     * @param $price 修改后的价格
     * @return  null
     */
    function modifySpec($rec_id,$new_spec_id,$specification,$price){
        Cart::where('rec_id',$rec_id)
            ->update(array(
                'spec_id'  =>  $new_spec_id,
                'specification'  =>  $specification,
                'price' => $price,
                'quantity'=>1
            ));
    }

    /**
     * 修改购物车
     * @param $rec_id 购物车id
     * @param $new_spec_id 修改后的规格id
     * @param $specification 修改后的规格信息
     * @param $price 修改后的价格
     * @param $quantity 修改的数量
     * @return  null
     */
    function modifyCart($rec_id,$new_spec_id,$specification,$price,$quantity){
        Cart::where('rec_id',$rec_id)
            ->update(array(
                'spec_id'  =>  $new_spec_id,
                'specification'  =>  $specification,
                'price' => $price,
                'quantity' => $quantity
            ));
    }

    /**
     * 从购物车删除商品 物理删除
     * @param $rec_id_list 需要删除的商品id数组
     * @param $user_id 用户id
     */
    public function deleteFromCart($rec_id_list,$user_id){
        DB::table('cart')
            ->whereIn('rec_id',$rec_id_list)
            ->where('user_id',$user_id)->delete();
    }

}
